package com.cloudpivot.receivales.contract.service.impl;

import com.cloudpivot.receivales.contract.configuration.CrmConfig;
import com.cloudpivot.receivales.contract.domain.bpm.BpmContractMain;
import com.cloudpivot.receivales.contract.entity.erpcontract.CrmContractPull;
import com.cloudpivot.receivales.contract.domain.crmcontract.CrmContract;
import com.cloudpivot.receivales.contract.domain.crmcontract.CrmContractClause;
import com.cloudpivot.receivales.contract.domain.oa.OAContract;
import com.cloudpivot.receivales.contract.domain.oa.OAContractClause;
import com.cloudpivot.receivales.contract.repository.erpcontract.CrmContractPullRepository;
import com.cloudpivot.receivales.contract.service.CrmContractService;
import com.cloudpivot.receivales.contract.service.http.HttpAPIServiceForCrm;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * crm合同服务
 */
@Service
@Slf4j
public class CrmContractServiceImpl implements CrmContractService {
    @Autowired
    private CrmContractPullRepository crmContractPullRepository;

    @Autowired
    private OAEntityToCrmEntityImpl oaEntityToCrmEntity;

    @Autowired
    private HttpAPIServiceForCrm httpApi;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private CrmConfig crmConfig;

    /**
     * 通过U8结果插入crm合同
     * 补充字段 用传入对象的方法
     *
     * @param strContractID U8数据库对应合同ID
     */
    @Override
    public String addContractByEntity(String strContractID, OAContract entity,String version) {
        String apiURL = String.format("%s%s", this.crmConfig.getCrmurl(), "new_main_contracts");
        log.info("请求地址:{}" , apiURL);
        List<CrmContractPull> contractPull = crmContractPullRepository.getCrmContractPulls(strContractID);
        /**
         * 如果合同客户找不到crm的guid，抛异常
         */
        if (contractPull.get(0).getCcusdefine7()==null) {
            log.info("crm新增合同时，无法找到客户guid，无法继续新增合同，请先维护客户");
            return null;
        }
        CrmContract crmContract = oaEntityToCrmEntity.toConvertEntityByU8(contractPull,version);
        //补充字段
        crmContract.setNew_sale_contract_type(entity.getSale_contract_type());
        crmContract.setNew_sale_compliance_type(entity.getSale_compliance_type());
        crmContract.setNew_compliance_state(entity.getCompliance_state());
        crmContract.setNew_contractstate(entity.getContractState());
        if(version.equals("3")){
            //如果版本为3的,增加辅助字段
            crmContract.setNew_system_version("3");
        }
        //条款明细 暂时不推送
//        crmContract.setContractClauses(oaCoverClause(entity.getClauseItems()));

        try {
            //请求推送crm
            String responseStr = httpApi.doPostCrm(apiURL, objectMapper.writeValueAsString(crmContract));

            String crmContractId="";
            if (responseStr != null) {
                Map<String, Object> responseMap = objectMapper.readValue(responseStr, Map.class);
                crmContractId = responseMap.get("new_main_contractid").toString();
                log.info("新插入的crm主合同id={}", crmContractId);
                return crmContractId;
            }else{
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();

            return null;
        }
    }

    /**
     * 更新crm合同 存放位置字段
     */
    public void updateCrmCFWZ(String cDefine13, String guid) {
        String url = String.format("%snew_main_contracts(%s)", this.crmConfig.getCrmurl(), guid);
        Map<String, String> map = new HashMap<>();
        map.put("new_cdefine13", cDefine13);

        try {
            httpApi.doUpdateCrm(url, objectMapper.writeValueAsString(map));
        } catch (Exception e) {
            e.printStackTrace();
            log.info("更新cdefine13字段异常");
        }
    }

    /**
     * 条款明细转换
     * @param item1
     *
     */
    private List<CrmContractClause>  oaCoverClause(List<OAContractClause> item1) {
        if (item1.isEmpty()) {
            return null;
        }
        List<CrmContractClause> list = new ArrayList<>();

        for (OAContractClause item : item1) {
            CrmContractClause clause = new CrmContractClause();
            clause.setNew_type(item.getTiaokuanlx());
            clause.setNew_property(item.getTiaokuansx());
            clause.setNew_quantity_describe(item.getQuantityInfo());
            clause.setNew_clause_remarks(item.getArticleinfo());
            clause.setNew_clause_describe(item.getHteongms());
            clause.setNew_unit(item.getLianghuadw());
            list.add(clause);
        }
        return list;
    }

    /**
     * 不用
     *
     * @param crmContract
     */
    @Override
    public void addContract(CrmContract crmContract) {

    }
}
